package com.ingenico.piccolo.event;

import java.awt.geom.Point2D;

import com.ingenico.insider.nodes.PMark;
import com.ingenico.insider.services.impl.SelectionControlSupplier;

import edu.umd.cs.piccolo.PLayer;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.util.PBounds;

public class PSelectionEventHandler extends PBasicInputEventHandler {
	/**
	 * The PMark that is managed by this event handler
	 */
	protected final PMark rectangle;

	/**
	 * The mouse press location for the current pressed, drag, release sequence
	 */
	protected Point2D pressPoint;

	/**
	 * The current drag location
	 */
	protected Point2D dragPoint;

	public PSelectionEventHandler(PMark rectangle, PLayer layer) {
		this.rectangle = rectangle;
	}

	public void mousePressed(PInputEvent e) {
		super.mousePressed(e);			

		// Initialize the locations.
		pressPoint = e.getPosition();
		dragPoint = pressPoint; 			

		// update the rectangle shape.
		updateRectangle();
	}

	public void mouseDragged(PInputEvent e) {
		super.mouseDragged(e);
		// update the drag point location.
		dragPoint = e.getPosition();	
		
		// update the rectangle shape.
		updateRectangle();
	}

	public void mouseReleased(PInputEvent e) {
		super.mouseReleased(e);
		
		if (pressPoint == dragPoint) {
			clearSelection();
		} else {
			final SelectionControlSupplier selectionControlSupplier = SelectionControlSupplier.getInstance();
			updateRectangle();
			selectionControlSupplier.getSelectionClearAction().setEnabled(true);
			selectionControlSupplier.getSelectionMarkAction().setEnabled(true);
		}
	}	

	public void updateRectangle() {
		// create a new bounds that contains both the press and current
		// drag point.
		PBounds b = new PBounds();
		b.add(pressPoint);
		b.add(dragPoint);

		// Set the rectangles bounds.
		rectangle.setBounds(b);
		rectangle.setVisible(true);
		rectangle.setPickable(true);
	}

	public PBounds getSelection() {
		return rectangle.getFullBounds();
	}

	public void clearSelection() {
		rectangle.setVisible(false);
		rectangle.setPickable(false);
		rectangle.setBounds(0, 0, 0, 0);
		
		final SelectionControlSupplier selectionControlSupplier = SelectionControlSupplier.getInstance();
		selectionControlSupplier.getSelectionClearAction().setEnabled(false);
		selectionControlSupplier.getSelectionMarkAction().setEnabled(false);
	}
}
